package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * 阅读量+
 */
@WebServlet("/addrcount")
public class AddReadCountServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg="未知错误";
        int data=0;
        //1.得到前端参数并进行效验
        String aidStr=req.getParameter("aid");
        //2.访问量+1，得到执行的结果
        if(!StrUtil.isBlank(aidStr)){
            int aid=Integer.valueOf(aidStr);
            if (aid>0){
            Connection connection= DBUtils.getConnection();
            String sql="update article set readcount=readcount+1 where aid=?";
            PreparedStatement statement=connection.prepareStatement(sql);
            statement.setInt(1,aid);
            data=statement.executeUpdate();
            //关闭资源
            DBUtils.close(null,statement,connection);
            msg="";
        }else {
            msg=("参数错误!");
        }
        }
            else{
                msg=("参数错误!");
        }
        //3.将结果返回给前那段
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,data,msg)));
    }

}
